/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#include "GimboConnectDialog.h"

#include <wx/msgdlg.h>
#include "lastAPs.hpp"
#include <sstream>

GimboConnectDialog::GimboConnectDialog( GimboLoaderFrame* parent, TGimboSettings *settings )
  : ConnectDialog( parent ),
    frame(parent),
    settings(settings)
{
  CLastAPs laps;

  // IF Reading failed, init with hard coded list;
  // FIXME: Read from some Gimbo configuration
  if (laps.ReadFiles() == false) {
    std::vector<std::string>::iterator i;
    for (i=settings->Hubs.begin();i!=settings->Hubs.end();i++) {
      laps.AddHostname(*i);
    }
    laps.AddHostname(settings->Hub);
    laps.AddPort(settings->Port);
  }

  THostnameArray ha = laps.GetLastHostnames();
  TPortArray pa = laps.GetLastPorts();

  if (!ha.empty()) {
    for(THostnameArray::const_iterator it = ha.begin();
        it != ha.end();
        ++it) {
      comboBox_Hub->Insert(*it, 0);  
    }
    comboBox_Hub->SetValue(ha.back());
  }

  if (!pa.empty()) {
    for(TPortArray::const_iterator it = pa.begin();
        it != pa.end();
        ++it) {
      std::stringstream r;
      r << *it;
      comboBox_Port->Insert(r.str(), 0);  
    }
    std::stringstream r;
    r << pa.back();
    comboBox_Port->SetValue(r.str());  
  }

  textCtrl_OwnName->SetValue(settings->OwnName);
}

void GimboConnectDialog::OnCancel( wxCommandEvent& event )
{
  EndModal(0);
}

void GimboConnectDialog::OnOK( wxCommandEvent& event )
{
  const std::string host = comboBox_Hub->GetValue().mb_str(wxConvUTF8);
  const std::string portstr = comboBox_Port->GetValue().mb_str(wxConvUTF8);

  long int port;
  if (!(comboBox_Port->GetValue().ToLong(&port))) {
    wxMessageBox(_T("Port value invalid."));
    return;
  }

  CLastAPs laps;
  laps.AddHostname(host);
  laps.AddPort(port);
  
  frame->Connect(host,
                 port,
                 (char*)(textCtrl_OwnName->GetValue().mb_str(wxConvUTF8)));
  
  EndModal(1);
  
}
